import subprocess
import re

def get_functions_from_ast(file_path):
    # 使用 Clang 生成 AST
    clang_command = ['clang', '-Xclang', '-ast-dump', '-fsyntax-only', file_path]
    try:
        # 获取 Clang 输出
        result = subprocess.run(clang_command, capture_output=True, text=True, check=True)
        ast_output = result.stdout
        
        # 正则表达式匹配函数信息
        function_pattern = re.compile(
            r'(?P<type>\S+)\s+(?P<name>\w+)\s*\(.*\)\s*{\s*'
            r'(?P<start_line>\d+).*?}'
        )

        functions = []
        for match in function_pattern.finditer(ast_output):
            function_info = match.groupdict()
            function_info['start_line'] = int(function_info['start_line'])
            functions.append(function_info)
        
        return functions

    except subprocess.CalledProcessError as e:
        print(f"Error running clang: {e}")
        return []

# 测试函数
if __name__ == "__main__":
    file_path = '/home/liushuai/arithmetic/third_party/coding/cxx/algorithm/backtrack/src/combinationSum.cc'  # 替换为你的文件路径
    functions = get_functions_from_ast(file_path)

    for func in functions:
        print(f"Function Name: {func['name']}")
        print(f"Return Type: {func['type']}")
        print(f"Start Line: {func['start_line']}")
        print('-' * 40)
